package cn.itwen.star.graph.core.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;

import java.security.Principal;
import java.util.List;

@Slf4j
public class WebsocketUerInterceptor implements ChannelInterceptor {
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        //判断当前请求是否是建立链接请求
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (accessor!=null && StompCommand.CONNECT.equals(accessor.getCommand())){
            //从连接头获取client Id
            List<String> clientIds = accessor.getNativeHeader("clientId");
            log.info("获取到客户端id clientId:" + clientIds);
            if (clientIds!=null && !clientIds.isEmpty()){
                //缓存客户端Id和通道的关系
                accessor.setUser(new Principal() {
                    @Override
                    public String getName() {
                        return clientIds.get(0);
                    }
                });
            }
        }
        return message;
    }
}
